package com.cisetech.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cisetech.util.FileOperateUtil;
import com.cisetech.util.ResponseMessage;



@Controller
public class Upload {
	ResponseMessage responseMessage = new ResponseMessage();
	@RequestMapping(value="/Upload/image",method=RequestMethod.POST)
	 public void addImage(HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "imgFile" ,required = false) MultipartFile[] imgFile) throws ServletException, FileUploadException { 
		String img = "";
		response.setContentType("application/json");  
		JSONObject Json = new JSONObject();
		PrintWriter out;
		if (imgFile != null && imgFile.length > 0) {
            for (int i = 0; i < imgFile.length; i++) {
                MultipartFile file = imgFile[i];
                // 保存文件
                img = saveFile(request, file); 
            }
            Map<String, String> map = new HashMap<String, String>();
            try {
            if("2".equals(img)){
            	Json.put("url", img);
            	out = response.getWriter();
            	out.print(Json.toString());
        		out.flush();
    		   	out.close();
    		   	out = null;
         		return;
            }
            
    		Json.put("error", 0);
    		Json.put("url", img);
			out = response.getWriter();
			out.print(Json.toString());
    		out.flush();
		   	out.close();
		   	out = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
	}
	  /***
     * 保存文件
     * @param file
     * @return
     */
    private String saveFile(HttpServletRequest request, MultipartFile file) {
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中  )
            	Calendar c = Calendar.getInstance();
            	UUID uuid = UUID.randomUUID();
            	SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            	String newFileName = df.format(new Date());
            	String filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/upload/img/"+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DAY_OF_MONTH)+"/"+uuid+".jpg";
                //String filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/upload/img/"+newFileName+"/"+ uuid+".jpg";
                System.out.println("filePath+++++++++++++" + filePath);
                File saveDir = new File(filePath);
                saveDir.mkdirs();
                if (!saveDir.getParentFile().exists())
                    saveDir.getParentFile().mkdirs();
                // 转存文件
                
                //String filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/upload/img/"+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DAY_OF_MONTH)+"/"+imgName+".jpg";
                FileOperateUtil.saveFiles(file,uuid+"",filePath);
                String img = "/upload/img/"+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DAY_OF_MONTH)+"/"+uuid+".jpg";//返回的为最后一张图片的路径

                //file.transferTo(saveDir);
                return img;
            } catch (Exception e) {
            	return "2";
            }
        }
		return null;
        
    }
  //图片上传
  	@ResponseBody
  	@RequestMapping(value="/Upload/image2",method=RequestMethod.POST)
  	public String image(@RequestParam(value = "image" ,required = false) MultipartFile[] image,
      		HttpServletRequest request,HttpServletResponse response){
  		String img="";
  		if (image != null && image.length > 0) {
              for (int i = 0; i < image.length; i++) {
                  MultipartFile file = image[i];
                  // 保存文件
                  String imgName = UUID.randomUUID().toString();
                  Calendar c = Calendar.getInstance();
                  String filePath = request.getSession().getServletContext().getRealPath("/") + "WEB-INF/upload/img/"+c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DAY_OF_MONTH)+"/"+imgName+".jpg";
                  FileOperateUtil.saveFiles(file,imgName,filePath);
                  img = c.get(Calendar.YEAR)+"/"+(c.get(Calendar.MONTH)+1)+"/"+c.get(Calendar.DAY_OF_MONTH)+"/"+imgName+".jpg";//返回的为最后一张图片的路径
              }
          }

  		return img;
  	}
}